#include "platform_abstraction.h"
#include <cstdlib>
#include <cstring>

namespace Base {
namespace Utils {
namespace Platform {

#ifdef _WIN32

int FileOpen(const char* path, int flags, int mode) {
    // Windows实现
    DWORD desiredAccess = 0;
    DWORD creationDisposition = 0;
    
    if (flags & O_CREAT) {
        creationDisposition = CREATE_ALWAYS;
    } else {
        creationDisposition = OPEN_EXISTING;
    }
    
    if (flags & O_RDWR) {
        desiredAccess = GENERIC_READ | GENERIC_WRITE;
    } else if (flags & O_WRONLY) {
        desiredAccess = GENERIC_WRITE;
    } else {
        desiredAccess = GENERIC_READ;
    }
    
    HANDLE handle = CreateFileA(path, desiredAccess, 0, NULL, 
                               creationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
    
    if (handle == INVALID_HANDLE_VALUE) {
        return -1;
    }
    
    return reinterpret_cast<intptr_t>(handle);
}

int FileClose(int fd) {
    HANDLE handle = reinterpret_cast<HANDLE>(fd);
    return CloseHandle(handle) ? 0 : -1;
}

ssize_t FileWrite(int fd, const void* buf, size_t count) {
    HANDLE handle = reinterpret_cast<HANDLE>(fd);
    DWORD bytesWritten = 0;
    
    if (WriteFile(handle, buf, static_cast<DWORD>(count), &bytesWritten, NULL)) {
        return static_cast<ssize_t>(bytesWritten);
    }
    
    return -1;
}

int FileSync(int fd) {
    HANDLE handle = reinterpret_cast<HANDLE>(fd);
    return FlushFileBuffers(handle) ? 0 : -1;
}

#else

int FileOpen(const char* path, int flags, int mode) {
    return open(path, flags, mode);
}

int FileClose(int fd) {
    return close(fd);
}

ssize_t FileWrite(int fd, const void* buf, size_t count) {
    return write(fd, buf, count);
}

int FileSync(int fd) {
    return fsync(fd);
}

#endif

// 内存操作实现（跨平台）
void* MemoryAllocate(size_t size) {
    return malloc(size);
}

void MemoryFree(void* ptr) {
    free(ptr);
}

void* MemoryAllocateAligned(size_t size, size_t alignment) {
#ifdef _WIN32
    return _aligned_malloc(size, alignment);
#else
    void* ptr = nullptr;
    if (posix_memalign(&ptr, alignment, size) == 0) {
        return ptr;
    }
    return nullptr;
#endif
}

void MemoryFreeAligned(void* ptr) {
#ifdef _WIN32
    _aligned_free(ptr);
#else
    free(ptr);
#endif
}

// 线程命名（简化实现）
void ThreadSetName(const char* name) {
#ifdef __linux__
    pthread_setname_np(pthread_self(), name);
#elif defined(__APPLE__)
    pthread_setname_np(name);
#elif defined(_WIN32)
    // Windows线程命名需要特殊处理
#endif
}

} // namespace Platform
} // namespace Utils
} // namespace Base
